package com.qikux.dao.impl;

import com.qikux.dao.UserDao;
import com.qikux.entity.User;
import org.haredot.annotation.Repository;
import org.haredot.callback.PreparedStatementSetter;
import org.haredot.utils.DBUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public User findUserByTel(String tel) {

        String sql = "select * from tb_user where tel = ? and del = 0" ;

        return DBUtils.query(sql, User.class, tel);
    }

    @Override
    public long saveUser(User user) {
        String sql = "insert into tb_user(tel, password, email, state, create_time) values(?, ?, ?, ? , now())" ;
        return DBUtils.insertAndGeneratorKeys(sql, new PreparedStatementSetter<Long>() {
            @Override
            public void bindParams(PreparedStatement ps) throws Exception {
                ps.setString(1, user.getTel());
                ps.setString(2, user.getPassword());
                ps.setString(3, user.getEmail());
                ps.setBoolean(4, false);
            }
            @Override
            public Long getGeneratorKey(ResultSet rs) throws Exception {
                return rs.getLong(1);
            }
        });
    }

    @Override
    public int updateBaseUser(User user) {
        String sql = "update tb_user set photo = #{photo}, nick_name = #{nickName}, real_name = #{realName}, " +
                "sex = #{sex}, update_time = now(), birth = #{birth} where id = #{id} and del = 0" ;
        return DBUtils.update(user, sql);
    }

    @Override
    public User findUserById(Long uid) {
        String sql = "select * from tb_user where id = ? and del = 0" ;
        return DBUtils.query(sql, User.class, uid);
    }

    @Override
    public int updateState(Long uid, int state) {
        String sql = "update tb_user set state = ? where id = ? and del = 0 and state = 0" ;
        return DBUtils.update(sql, state, uid);
    }
}
